const loginA = document.querySelector('.login-a');//跳转到注册
const registerA = document.querySelector('.register-a');//跳转到登录
const registerForm = document.querySelector('.register form');//注册的form
const loginForm = document.querySelector('.login form');//登录的form
const registerBtn = document.querySelector('.register button')//注册的按钮
const loginBtn = document.querySelector('.login button');//登录的按钮

//注册登录点击切换
loginA.addEventListener('click', function (e) {
    document.querySelector('.login').style.display = "none"
    document.querySelector('.register').style.display = "block"
})
registerA.addEventListener('click', function (e) {
    document.querySelector('.register').style.display = "none"
    document.querySelector('.login').style.display = "block"
})


//点击提交按钮   注册功能
registerForm.addEventListener('submit', function (e) {
    e.preventDefault()
    // console.log('a');
    const data = serialize(registerForm, { hash: true, empty: true })
    if (!/[a-zA-Z0-9_]{2,15}/.test(data.username)) {
        alert('用户名不正确，请输入长度2~15位')
        return
    }
    if (!/[a-zA-Z0-9_]{6,15}/.test(data.password)) {
        alert('密码不正确，请输入长度6~15位')
        return
    }
    // console.log(data);
    axios({
        method: 'post',
        url: '/api/register',
        data
    }).then((result) => {
        // console.log(result.message);
        if (result.code === 0) {
            toastr.success(result.message)
            registerA.click()
        } else {
            toastr.error(result.message)
        }


    }).catch((error) => {
        console.dir(error);
        toastr.error('请求错误')
    })
})
//登录功能
loginForm.addEventListener('submit', function (e) {
    e.preventDefault()
    const data = serialize(loginForm, { hash: true, empty: true })
    if (!/[a-zA-Z0-9_]{2,15}/.test(data.username)) {
        alert('用户名不正确，请输入长度2~15位')
        return
    }
    if (!/[a-zA-Z0-9_]{6,15}/.test(data.password)) {
        alert('密码不正确，请输入长度6~15位')
        return
    }
    // console.log(data);
    axios({
        method: 'post',
        url: '/api/login',
        data
    }).then((result) => {
        // console.log(result.token);
        if (result.code === 0) {
            //获取token到本地存储
            localStorage.setItem('token', result.token)
            toastr.success(result.message)
            setTimeout(() => {
                location.href = 'dashboard.html'
            }, 1500)
        } else {
            toastr.error(result.message)
        }
    }).catch((error) => {
        console.dir(error);
        toastr.error('请求错误')
    })
})
